<template>
	<view>
		<!-- checkDataSum：选择文件数量
		 selectedHandler：选择的文件
		 succesHandler：成功回调
		 failHandler：失败回调 -->
		<yt-uploads ref="uploads" :suffixName="suffixName" :checkDataSum="checkDataSum" @selected="selectedHandler" @success="succesHandler"
		 @fail="failHandler" @process="processHandler"></yt-uploads>

		<!-- 列表 -->
		<view class="relative-border">
			<view v-for="(item,index) in dataList" :key="index" :class="{'invencurrent':(currentIndex === index)}">
				<view class="invent-listcon" @click="invent(index,item)">
					<view class="invent-oddnumber">
						{{index + 1}}盘点单号 : {{item.checkBill}}
					</view>
					<view class="invent-content">
						<view>
							开始时间: {{item.startDate}}
						</view>
						<view>
							设备总数:{{item.zongshu}}已盘:{{item.yipan}}未盘:{{item.weipan}}盘盈:{{item.panyin}}
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮 -->
		<!-- flexinven-button-->
		<view class="eam-box">
			<u-row gutter="16" class="flexinven-con">
				<u-col span="3">
					<view class="flexinven-flex" @click="selectFileHandler">获取文件</view>
				</u-col>
				<u-col span="3">
					<view class="flexinven-flex" @click="delDevicaCheck">删除</view>
				</u-col>
				<u-col span="3">
					<view class="flexinven-flex" @click="uploadDevicaCheck">上传</view>
				</u-col>
				<u-col span="3">
					<view class="flexinven-flex" @click="eamDevicaCheckForm">开始盘点</view>
				</u-col>
			</u-row>
		</view>
	</view>
</template>

<script>
	import ytUploads from "@/components/yt-uploads/yt-uploads.vue"
	import formatter from "../../../common/formatter.js"
	import filePlugin from '@/plugins/filePlugin';
	var Utils = uni.requireNativePlugin("UtilsModulePlugin")
	var _this;
	export default {
		data() {
			return {
				checkDataSum: 1,
				suffixName: '.jyw',
				selectList: [],
				selectData: {},
				dataList: [],
				mapList: [],
				currentIndex: '',
				start: false
			}
		},
		components: {
			ytUploads
		},
		onShow() {
			_this = this
			this.findList()
		},
		methods: {
			// 选择事件
			invent(index, item) {
				if (this.currentIndex === index) {
					this.currentIndex = null
					return
				}
				this.currentIndex = index
				this.selectData = item
			},
			// 查询数据
			findList() {
				console.log('findList');
				plus.sqlite.selectSql({
					name: 'first',
					sql: "SELECT a.id as id,a.checkBill as checkBill,max(a.startDate) as startDate,(SELECT count(1) FROM EamDeviceCheckDetails where checkId = a.id) as zongshu,(SELECT count(1) FROM EamDeviceCheckDetails where checkId = a.id and checkResult = '2') as panyin,(SELECT count(1) FROM EamDeviceCheckDetails where checkId = a.id  and checkResult = '3') as pankui,(SELECT count(1) FROM EamDeviceCheckDetails where checkId = a.id  and checkResult in ('1','2','3','4')) as yipan,(SELECT count(1) FROM EamDeviceCheckDetails where checkId = a.id  and checkResult = '0') as weipan FROM EamDeviceCheck a GROUP by a.id,a.checkBill",
					success: function(data) {
						_this.dataList = data
					},
					fail: function(e) {
						console.log('findList failed: ' + JSON.stringify(e));
					}
				});
			},
			// 跳转
			eamDevicaCheckForm() {
				if (this.$validate.isNull(this.selectData)) {
					uni.showModal({
						content: '请选择盘点单',
						showCancel: false
					});
					return
				}
				console.log(this.selectData.checkBill)
				console.log(this.selectData.id)
				uni.redirectTo({
					url: '/pages/eam/eamDeviceCheck/eamDeviceCheckForm?checkBill=' + this.selectData.checkBill + '&checkId=' + this.selectData
						.id
				});
			},
			// 删除盘点单
			delDevicaCheck() {
				if (this.$validate.isNull(this.selectData)) {
					uni.showModal({
						content: '请选择盘点单',
						showCancel: false
					});
					return
				}
				uni.showModal({
					content: '确定删除该盘点单',
					success: function(res) {
						if (res.confirm) {
							plus.sqlite.executeSql({
								name: 'first',
								sql: "delete from EamDeviceCheck where id = '" + _this.selectData.id + "'",
								success: function(e) {
									console.log('del EamDeviceCheck success!');
								},
								fail: function(e) {
									console.log('del EamDeviceCheck failed: ' + JSON.stringify(e));
								}
							});
							plus.sqlite.executeSql({
								name: 'first',
								sql: "delete from EamDeviceCheckDetails where checkId = '" + _this.selectData.id + "'",
								success: function(e) {
									console.log('del EamDeviceCheckDetails success!');
								},
								fail: function(e) {
									console.log('del EamDeviceCheckDetails failed: ' + JSON.stringify(e));
								}
							});
							let t = setTimeout(() => {
								_this.findList()
								_this.selectData = []
							}, 500)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			// 上传
			uploadDevicaCheck() {
				let eamDeviceCheck = []
				let eamDeviceCheckDetails = []
				let data = {}
				plus.sqlite.selectSql({
					name: 'first',
					sql: "select * from EamDeviceCheck",
					success: function(e) {
						console.log('select EamDeviceCheck success!');
						eamDeviceCheck = e
						plus.sqlite.selectSql({
							name: 'first',
							sql: "select * from EamDeviceCheckDetails",
							success: function(e) {
								console.log('select EamDeviceCheckDetails success!');
								eamDeviceCheckDetails = e
								data.EamDeviceCheck = eamDeviceCheck
								data.EamDeviceCheckDetails = eamDeviceCheckDetails
								console.log(Utils)
								Utils.writeCsv({
									"path": '/storage/emulated/0/Download/eamCsvFileApp',
									"dataList": data
								}, (res) => {
									uni.showModal({
										content: '文件路径：' + res.res,
										showCancel: false
									});
								})
							},
							fail: function(e) {
								console.log('select EamDeviceCheckDetails failed: ' + JSON.stringify(e));
							}
						});
					},
					fail: function(e) {
						console.log('select EamDeviceCheck failed: ' + JSON.stringify(e));
					}
				});
			},
			//读取文件
			dqFile(filePath){
				 uni.getFileSystemManager().readFile({
				   filePath: 'path/to/file',  // 文件路径
				   encoding: 'utf8',  // 读取的文件编码格式
				   success: function(res) {
				     let content = res.data;  // 文件内容
				     console.log(content);
				   },
				   fail: function(error) {
				     console.log(error);
				   }
				 });
			},
			// 处理zip文件
			onOpenZip() {
				uni.showLoading({
					title: '数据导入加载中'
				});
				uni.hideLoading();
				console.log(this.selectList[0].path)
				this.dqFile(this.selectList[0].path)
				Utils.ReadZipFile({
					"filePath": this.selectList[0].path
				}, (res) => {
					console.log(this.selectList[0].path)
					console.log(_this.mapList)
					_this.mapList = res.res
					console.log(_this.mapList)
					_this.mapList.forEach((item) => {
						for (var key in item) {
							// 删除表格
							plus.sqlite.executeSql({
								name: 'first',
								sql: 'delete from ' + key,
								success: function(e) {
									console.log('executeSql success!');
								},
								fail: function(e) {
									console.log('executeSql failed: ' + JSON.stringify(e));
								}
							});
							// 创建表格添加数据
							item[key].forEach((value, index) => {
								if (index === 0) {
									let f = "";
									value.forEach((v, index) => {
										if (index !== (value.length - 1)) {
											f += '"' + v + '" CHAR(100), '
										} else {
											f += '"' + v + '" CHAR(100) '
										}
									})
									let sql = "create table if not exists " + key + "( " + f + ")";
									plus.sqlite.executeSql({
										name: 'first',
										sql: sql,
										success: function(e) {
											console.log('executeSql success!');
										},
										fail: function(e) {
											console.log('executeSql failed: ' + JSON.stringify(e));
										}
									});
								} else {
									let sql = "insert into " + key + " values('" + value.join("','") + "')";
									plus.sqlite.executeSql({
										name: 'first',
										sql: sql,
										success: function(e) {
											console.log('device_check insert success!');
										},
										fail: function(e) {
											console.log('device_check insert failed: ' + JSON.stringify(e));
										}
									});
								}
							})
						}
					})
					let t = setTimeout(() => {
						_this.findList()
						uni.hideLoading();
					}, 500)
				})
			},
			selectFileHandler() { // 选择文件方法调用组件的select方法
				// 初始化数据
				this.selectList = []
				this.start = false
				this.$refs.uploads.select()
			},
			selectedHandler(ret) { // 组件选择文件回调 返回值 [{path:"文件路径",state:0,size:"文件大小"}...]
				this.selectList = ret
				this.onOpenZip()
				console.log("seleted", JSON.stringify(ret))
			},
			processHandler(ret) { // 组件每个文件的上传状态 返回值{index:0,state:1(上传成功)|2(上传失败)}
				this.$set(this.selectList[ret.index], "state", ret.state)
				console.log("processing", ret)
			},
			succesHandler(ret) { // 所有文件上传结束后回调 返回值 [{ajax返回的数据}...]
				console.log("success", ret)
			},
			failHandler(ret) { // 失败回调 返回值 {type:0,data:"错误信息"} 上传失败不会在这里显示错误信息，统一在success中处理
				console.log("fail", ret)
			}
		}
	}
</script>

<style lang="less" scoped>
	.invencurrent {
		background-color: #f3f2f5;
	}
	.eam-box{
		position: fixed;
		left: 0;
		right: 0;
		bottom: 50px;
		background-color: #fff;
		z-index: 9;
		.flexinven-con {
			height: 70rpx;
			line-height: 70rpx;
			margin: 20rpx 0;
			padding: 0 10rpx;
			// 背景蓝色
			.flexinven-flex {
				text-align: center;
				color: #fff;
				font-size: 14px;
				background-color: #62c2f5;
				border-radius: 5px;
				cursor: pointer;
			}
		}
	}
</style>
